package com.changgou.service.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.service.file.utils.FastDFSClient;
import com.changgou.service.file.utils.FastDFSFile;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public Result uolaodFile(MultipartFile file){
        try {
            //判断文件是否存在
            if(file==null){
                throw new RuntimeException("文件不存在");
            }
            //获取文件完整名称
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)){
                throw new RuntimeException("文件不存在");
            }
            //提取文件拓展名
            int i = originalFilename.lastIndexOf(".");
            String extName = originalFilename.substring(i);
            //获取文件内容
            byte[] content = file.getBytes();
            //创建文件上传封装类
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, content, extName);
            //基于工具上传，并接收返回参数
            String[] upload = FastDFSClient.upload(fastDFSFile);
            //封装返回结果
            String url = FastDFSClient.getTrackerUrl() + upload[0] + "/" + upload[1];
            return new Result(true,StatusCode.OK,"文件长传成功",url);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"文件上传失败");
        }
    }
}
